import React, {Component} from 'react';
import AdvancedSearch from 'components/advanced-search';
import {Col, Icon, Row, Spin, Button} from 'antd';
import {deepCopy, messages, removeArrayItemByKey} from 'share/common';
import 'styles/data-center/report/custom-report/custom-report.scss';
import CustomReportService from 'containers/data-center/report-management/custom-report/custom-report.service';
import UniversalReportService from 'containers/data-center/report-management/custom-report/graphic/default-value/custom-report.service';
import {connect} from 'react-redux';
import Graphic from 'containers/data-center/report-management/custom-report/graphic';
import { handleDefaultValue } from 'containers/data-center/report-management/custom-report/graphic/default-value/default-value.service';
import debounce from 'lodash.debounce';
import {clearPending} from 'share/httpFetch';

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    tenant: state.login.tenant
  }
}

@connect(mapStateToProps)

class CustomReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      btnLoading: false,
      pageData: {},
      searchForm: [],
      searchFormMap: {},
      searchParamsData: [],
      customReportName: '',
      widgetList: [],
      isPreView: false,
      forceRefresh: false,
      criteriaData: {},
      sourceReportIdArray: [],
      pinnedList: [],
      isFetchingData: false,
      isManualSearch: false, //是否是 主动 搜索

      //联动处理  三个 map
      chartsRelativeMap: {}, // 1.map  每个图形表 关联的 图形表
      chartLinkableParamsMap: {}, // 2.map 每个图形表 接收到的筛选参数
      chartLinkablePropsMap: {},  // 3.map 每个图形表 联动纬度的 linkageColumnPropName

      currentReportPrivate: {}, // 各报表私有配置的载体 (不知道这是干嘛的)
    };
    this.turnOffForce = debounce(this.turnOffForce, 500);
    this.promiseList = [];
    this.getAllPromise = debounce(this.getAllPromise, 10);
  }

  componentWillMount() {

  }

  componentDidMount() {
    this.initData();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.params.id !== this.props.params.id) {
      this.initData(nextProps.params.id);
    }
  }

  initData = (nextId) => {
    this.setState({loading: true})
    const { params, route } = this.props;
    let isPreView = route.path.indexOf('custom-report-preview') !== -1;
    CustomReportService.getCustomReportDetail(nextId || params.id).then((res)=>{
      if (res.status === 200) {
        let copyData = deepCopy(res.data);
        let reportCharts = copyData.reportCharts;
        let sourceReportIdArray = [];
        if (reportCharts && reportCharts.length)
          res.data.reportCharts.forEach((item,index)=>{
            reportCharts[index].uniqueKey = item.id;
            reportCharts[index].key = item.chartType;
            reportCharts[index].set = true;
            if (item.chartType !== 'criteria')
              sourceReportIdArray.push(item.sourceReportId)
          })
        let widgetList = reportCharts && reportCharts.length && reportCharts.filter(item=>item.key !== 'criteria') || [];
        let criteriaData = reportCharts && reportCharts.length && reportCharts.filter(item=>item.key === 'criteria') || [];
        let searchForm = this.handleSearchForm(criteriaData[0] || {});
        let searchFormMap = this.handleSearchFormMap(criteriaData[0] || {});
        let chartsRelativeMap = this.handleChartsRelativeMap(widgetList);
        let chartLinkableParamsMap = this.handleChartLinkableParamsMap(widgetList);
        let chartLinkablePropsMap = this.handleChartLinkablePropsMap(widgetList);
        sourceReportIdArray = sourceReportIdArray.filter((item, index, self) => self.indexOf(item) === index);
        this.setState({
          pageData: res.data,
          customReportName: res.data.reportName,
          widgetList,
          criteriaData: criteriaData[0],
          searchFormMap,
          searchForm,
          isPreView,
          sourceReportIdArray,
          chartsRelativeMap,
          chartLinkableParamsMap,
          chartLinkablePropsMap,
          loading: false
        }, ()=>{this.advancedSearchRef && this.advancedSearchRef.search()})
      }
    })
  }

  handleChartLinkablePropsMap = (widgetList) => {
    let result = {};
    widgetList.forEach((item)=>{
      if (!(['criteria', 'detail_list', 'indicatrix'].indexOf(item.key) !== -1)) {
        result[item.id] = item.reportChartDetails.filter(item=>item.fieldType === 'dimension')[0].linkageColumnPropName;
      }
    })
    return result
  }

  handleChartLinkableParamsMap = (widgetList) => {
    let result = {};
    widgetList.forEach((item)=>{
      result[item.id] = [];
    })
    return result
  }

  handleChartsRelativeMap = (widgetList) => {
    let result = {};
    widgetList.forEach((item)=>{
      result[item.id] = item.reportChartLinkages.map(item=>item.targetReportChartId);
    })
    return result
  }

  handleSearchFormMap = (data) => {
    let detailsArray = deepCopy(data.reportChartDetails);
    let result = {};
    detailsArray && detailsArray.forEach((item)=>{
      result[`${item.sourceReportId}_${item.criteriaPropName}`] = {
        sourceReportId: item.sourceReportId,
        criteriaCode: item.criteriaCode,
        criteriaPropName: item.criteriaPropName,
        reportId: item.reportId,
        values: []
      }
    })
    return result
  }

  handleSearchForm = (data) => {
    let result = []
    if (data && data.reportChartDetails && data.reportChartDetails.length) {
      result = UniversalReportService.searchFormFactory({
        context: this,
        list: data.reportChartDetails.map((item)=>{
          return {
            criteriaCode: item.criteriaCode,
            criteriaName: item.fieldDisplayName,
            criteriaPropName: `${item.sourceReportId}_${item.criteriaPropName}`,
            defaultValue: item.defaultValue
          }
        })
      })
    }
    return result
  }

  componentWillUnmount() {
    clearPending();
  }

  handleSearch = (value, entity) => {
    this.setState({isFetchingData: true, btnLoading: true})
    const { searchFormMap } = this.state;
    let params = [];

    Object.keys(value).forEach((item)=>{
      let result = handleDefaultValue(entity[item], {criteriaCode: searchFormMap[item].criteriaCode})
      if (result && result.length) {
        let single = deepCopy(searchFormMap[item]);
        single.values = result;
        params.push(single);
      }
    })
    this.setState({searchParamsData: params, isManualSearch: true, forceRefresh: true}, ()=>{
      this.turnOffForce();
    })
  }

  turnOffForce = () => {
    this.setState({forceRefresh: false})
  }

  //返回到列表
  handleBack = () => {
    window.history.go(-1);
  };

  //图标被点击啦
  handleChartClick = ({ item, chartIndex, reportKey, active }, sourceReportId) => {
    const { chartsRelativeMap, chartLinkableParamsMap, chartLinkablePropsMap } = this.state;
    let copyChartLinkableParamsMap = deepCopy(chartLinkableParamsMap);
    let hasRelated = false;
    if (active) {   //激活联动
      let data = {
        orderManId: reportKey,
        criteriaCode: undefined,
        criteriaPropName: chartLinkablePropsMap[reportKey],
        sourceReportId: sourceReportId,
        linkageSearch: true,
        values: [
          {
            value: item.data.data[chartLinkablePropsMap[reportKey]]
          }
        ]
      }
      chartsRelativeMap[reportKey].forEach((chartId)=>{
        hasRelated = true;
        copyChartLinkableParamsMap[chartId] = removeArrayItemByKey(chartLinkableParamsMap[chartId] || [], {orderManId: reportKey}, 'orderManId') || [];
        copyChartLinkableParamsMap[chartId].push(data)
      })
    } else { //取消联动
      chartsRelativeMap[reportKey].forEach((chartId)=>{
        hasRelated = true;
        copyChartLinkableParamsMap[chartId] = removeArrayItemByKey(chartLinkableParamsMap[chartId], {orderManId: reportKey}, 'orderManId') || [];
      })
    }
    this.setState({chartLinkableParamsMap: copyChartLinkableParamsMap, isFetchingData: hasRelated, btnLoading: hasRelated})
  }

  onChangePinnedList = pinnedList => {
    this.setState({ pinnedList });
  };

  handleOverPromise = (item) => {
    this.promiseList.push(item);
    this.getAllPromise()
  }

  getAllPromise = () => {
    let promiseList = Promise.all(this.promiseList)
    promiseList.catch(()=>{
      this.resetDataLoading();
    }).finally(()=>{
      // console.log('请求完毕')
      this.resetDataLoading();
    })
  }

  resetDataLoading = () => {
    this.promiseList = []
    this.setState({btnLoading: false, isFetchingData: false})
  }

  render() {

    const { isPreView, searchForm, widgetList, searchParamsData, chartLinkableParamsMap,
      isManualSearch, pageData, pinnedList, forceRefresh, isFetchingData, btnLoading, loading } = this.state;

    let reportName = this.props.params.reportName || messages('basic-10.key191')/*报表详情*/;

    return (
      <div className='custom-report-container'>
        <Spin spinning={loading}>
          <div className="search-wrapper">
            {searchForm.length ?
              <AdvancedSearch
                tableName={pageData.id}
                onSearch={this.handleSearch}
                pinnedList={pinnedList}
                onChangePinnedList={this.onChangePinnedList}
                title={reportName}
                searchButton={{
                  props: { type: 'primary', loading: btnLoading },
                  text: messages('common.search')/*搜索*/
                }}
                onRef={ref => this.advancedSearchRef = ref}
                getForm={form => this.advancedSearchFormRef = form}
                searchForm={searchForm}
                notLoadWhenMount
              /> : null
            }
            {
              (!searchForm || !searchForm.length) &&
              <div className='report-title'>
                {reportName}
              </div>
            }
          </div>
          <div className="charts-container">
            <Row gutter={16} type="flex">
              {widgetList.map((item, index) => <Col span={item.showScreen === 'half' ? 12 : 24}
                                                    key={item.id}
                                                    order={index + 1}
                                                    style={{ minWidth: item.showScreen === 'half' ? '434px' : '884px' }}>
                <Graphic
                  noEdit
                  key={item.id}
                  displayMode={true}
                  forceRefresh={forceRefresh}
                  isPreView={isPreView}
                  isManualSearch={isManualSearch}
                  isFetchingData={isFetchingData}
                  chartLinkableParams={chartLinkableParamsMap[item.id]}
                  searchParamsData={searchParamsData}
                  onRef={ref => this.GraphicRef = ref}
                  widget={Object.assign({}, item)}
                  onChartClick={this.handleChartClick}
                  handleOverPromise={this.handleOverPromise}
                />
              </Col>)}
            </Row>
          </div>
          {window.history.length > 1 && widgetList && widgetList.length > 0 &&
          <div className='new-bottom-back'>
            <Button onClick={this.handleBack}>{messages('common.back')/*返回*/}</Button>
          </div>
          }
        </Spin>
      </div>
    );
  }
}

CustomReport.propTypes = {};

export default CustomReport;
